import React, { useEffect, useRef } from 'react';
import {
  getTargetElement,
  useIntersectionObserver,
} from './intersection-observer';

export type LazyLoadProps = {
  children: React.ReactNode;
  /** 可见性回调 */
  onVisible?: (visible: any) => void;
  /** 滚动容器, 默认浏览器视窗 */
  container?: Element | Document | null | undefined;
  /** 容器外边距 */
  margin?: string;
  /** 相交的程度 */
  threshold?: number | number[];
};
const isFunction = (value: unknown): boolean => typeof value === 'function';

export const LazyLoad = ({
  children,
  onVisible,
  container,
  margin,
  threshold,
}: LazyLoadProps) => {
  const ChildRef = useRef(null);
  const [observerEntry, listen] = useIntersectionObserver();

  useEffect(() => {
    isFunction(onVisible) && onVisible?.(observerEntry?.isIntersecting);
  }, [observerEntry]);

  useEffect(() => {
    if ((children as React.ReactNode[])?.length > 1) {
      console.warn('LazyLoad children should be one.');
    }
    listen({
      rootMargin: margin,
      root: getTargetElement(container),
      threshold,
      element: getTargetElement(ChildRef) as Element,
    });
  }, []);

  return <div ref={ChildRef}>{children}</div>;
};
